package com.cg.asm.core.config.security;

import com.cg.asm.core.domain.vo.user.UserLoginVO;
import com.cg.asm.core.util.AsmApiUtils;
import lombok.extern.java.Log;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

@Log
@Component
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    // 通过验证
    private final String PASSED = "ROLE_REQUEST_PASSED";
    // 拒绝访问
    private final String DENIED = "ROLE_REQUEST_DENIED";

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        UserLoginVO userLoginVO = AsmApiUtils.getCurrentUserLoginVO();
        if (null != userLoginVO) {
            if ("super".equals(userLoginVO.getUsername())) {
                return SecurityConfig.createList(PASSED);
            } else {
                List<String> roles = userLoginVO.getRoles();
                if (null != roles && roles.size() != 0) {
                    return SecurityConfig.createList(PASSED);
                } else {
                    return SecurityConfig.createList(DENIED);
                }
            }
        }
        //用户信息为空，则为非法访问，转向登录页面
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
